﻿using System;
using System.Linq;
using System.Runtime.Caching;

namespace Framework.Common.Cache.ICacheImplement
{
    /// <summary>
    /// cache in memory
    /// </summary>
    //[Export(typeof(ICache))]
    public class InMemoryCache : ICache
    {
        #region private member

        private readonly MemoryCache _mc;

        #endregion

        #region constructor

        /// <summary>
        /// 
        /// </summary>
        public InMemoryCache()
        {
            _mc = MemoryCache.Default;
        }

        #endregion

        #region ICache

        public bool Add(string key, object value)
        {
            return _mc.Add(key, value, new DateTimeOffset(DateTime.MaxValue));
        }

        public bool Add(string key, object value, DateTime expiredTime)
        {
            return _mc.Add(key, value, new DateTimeOffset(expiredTime));
        }

        public bool Contains(string key)
        {
            return _mc.Contains(key);
        }

        public int Count
        {
            get { return _mc.Count(); }
        }

        public void Flush()
        {
            _mc.Trim(100);
        }

        public object GetData(string key)
        {
            return _mc.Get(key);
        }

        public T GetData<T>(string key)
        {
            object obj = GetData(key);
            if (obj != null)
            {
                return (T) obj;
            }
            return default(T);
        }

        public bool Remove(string key)
        {
            _mc.Remove(key);
            return true;
        }

        #endregion
    }
}